# This PowerShell script was released under the Ms-PL license
# http://www.opensource.org/licenses/ms-pl.html
# This script was originally intended for use with Microsoft Dynamics AX 2009
# and maintained and distributed as a project on CodePlex
# http://dynamicsaxbuild.codeplex.com


# Expecting SOURCEPATH, BINARIESPATH and optional filename for the combined XPO
param(
	[string] $SOURCEPATH = $(throw "XPO Source Path Required"),
	[string] $BINARIESPATH = $(throw "Combined XPO Output Path Required"),
	[string] $COMBINEDXPOFILENAME = "Combined.xpo"
	)

$XPOSTARTLINE1 = "Exportfile for AOT version 1.0 or later"
$XPOSTARTLINE2 = "Formatversion: 1"
$XPOENDLINE1 = "***Element: END"

# Write out the XPO file headers
$XPOSTARTLINE1 | out-file -encoding Unicode ($BINARIESPATH + "`\" + $COMBINEDXPOFILENAME)
$XPOSTARTLINE2 | out-file -append -encoding Unicode ($BINARIESPATH + "`\" + $COMBINEDXPOFILENAME)
"" | out-file -append -encoding Unicode ($BINARIESPATH + "`\" + $COMBINEDXPOFILENAME)

# Get a list of all XPO files in the source path, including subfolders
$files = Get-ChildItem -Recurse $SOURCEPATH -filter "*.xpo"
if ($files -ne $null)
{
	foreach ($file in $files)
	{
	# Make sure it's not a directory
		$fileType = ((Get-Item -literalPath $file.FullName).Mode)[0]
		if ($fileType -ne "d")
		{
	# Output the file content, filtering out the start and end lines of the XPO format
			$xpoText = Get-Content -Encoding Unicode -LiteralPath $file.FullName
			$xpoText = $xpoText | Select-String -Encoding Unicode -SimpleMatch -NotMatch $XPOENDLINE1
			$xpoText = $xpoText | Select-String -Encoding Unicode -SimpleMatch -NotMatch $XPOSTARTLINE1
			$xpoText = $xpoText | Select-String -Encoding Unicode -SimpleMatch -NotMatch $XPOSTARTLINE2
			$xpoText | out-file -width 99999 -append -encoding Unicode ($BINARIESPATH + "`\" + $COMBINEDXPOFILENAME)
		}
	}
}

#Write out the XPO end statement
$XPOENDLINE1 | out-file -append -encoding Unicode ($BINARIESPATH + "`\" + $COMBINEDXPOFILENAME)
